import React from 'react'
import { Table, Button } from 'antd';
import axios from 'axios'
import BaseModal from '../components/baseModal'

export default class App extends React.Component {
  state = {
    visible: false,
    formInfo: {},
    selectedRowKeys: [], // Check here to configure the default column
    loading: false,
    columns: [
      {
        title: 'ID',
        dataIndex: 'id',
      },
      {
        title: '姓名',
        dataIndex: 'username',
      },
      {
        title: '理论成绩',
        dataIndex: 'theory',
      },
      {
        title: '技能成绩',
        dataIndex: 'skill',
      },
      {
        title: 'Action',
        key: 'action',
        render: (text, record) => (
          <>
            <Button onClick={() => {
              this.setState({
                visible: true,
                isEdit: 'edit',
                formInfo: record
              }, () => {
                // 宏任务  微任务  dom渲染-线程
                setTimeout(() => { // 宏任务
                  this.refs.myModal.refs.baseForm.refs.form.setFieldsValue(this.state.formInfo)
                }, 0)
              })
              // console.log("modal:", this.refs.myModal)
            }} style={{ marginRight: '5px' }} size="small" type="primary">编辑</Button>
            <Button size="small" type="ghost">删除</Button>
          </>
        ),
      },
    ],
    tableArr: [],
    total: 0,
    current: 1,
    isEdit: null
  }

  componentDidMount() {
    this.getPageList({})
  }

  // 分页接口 -
  getPageList = async ({ page = 0, size = 5 }) => {
    let data = await axios.get('/api/pageGrade', { params: { page, size } })
    // console.log(data, 'dat阿芬页面')
    let list = data.data.data
    let total = data.data.total
    list.forEach(item => {
      item.key = item.id
    })
    this.setState({ tableArr: list, total, })
  }

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  // 分页按钮跳转
  onPageChange(val) {
    // console.log('val:', val)
    this.setState({
      current: val.current
    })
    this.getPageList({ page: val.current - 1 })
  }

  // 关闭弹出框，获得表单数据 ，提交给后端接口
  closeModal = async (val) => {
    console.log("val:", val)
    if (val === null) {
      this.setState({ visible: false })
      return;
    }
    const { isEdit } = this.state;
    const { current } = this.state;
    /** username theory skill  为了处理最后获取到传给后端的结果，*/
    let objValue = {
      ...this.state.formInfo, ...val
    }

    console.log("objValue:更改后需要提交给后端的数据：", objValue)

    switch (isEdit) {
      case "add":
        let addData = await axios.post('/api/addGrade', objValue)
        if (addData.data.code === 0) {
          // 点击当前页面，根据记录的按钮页码去请求后端数据，
          this.getPageList({ page: current - 1 })
        }
        break;
      case "edit": // id theory skill
        let editData = await axios.post('/api/updateGrade', objValue)
        if (editData.data.code === 0) {
          // 点击当前页面，根据记录的按钮页码去请求后端数据，
          this.getPageList({ page: current - 1 })
        }
        break;
      default:
        console.log('匹配失败')
    }
    this.setState({ visible: false })
  }

  render() {
    const {
      selectedRowKeys,
      columns,
      visible,
      tableArr,
      total,
      current,
      isEdit,
      formInfo
    } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    // const hasSelected = selectedRowKeys.length > 0;
    return <div>
      <Button onClick={() => {
        this.setState({ visible: true, isEdit: 'add' })
        setTimeout(() => {
          this.refs.myModal.refs.baseForm.refs.form.setFieldsValue({
            username: '',
            theory: '',
            skill: '',
            stuid: ''
          })
        }, 0)
      }}>增加数据</Button>
      {/* 弹出框 */}

      <BaseModal
        ref="myModal"
        formInfo={formInfo}
        isEdit={isEdit}
        visible={visible}
        closeModal={(val) => this.closeModal(val)}
      ></BaseModal>

      {/* 表单 */}
      <Table
        rowSelection={rowSelection}
        columns={columns}
        dataSource={tableArr}
        onChange={(val) => this.onPageChange(val)}
        pagination={{ pageSize: 5, current, total }}
      />

      {/* <div style={{ marginBottom: 16 }}>
        <span style={{ marginLeft: 8 }}>
          {hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}
        </span>
      </div> */}
    </div>
  }
}
